package com.lagou.builder;

import com.lagou.config.MethodType;
import com.lagou.config.Configuration;
import com.lagou.config.MapperStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * mapper.xml解析类
 * @author shenguotao
 */
public class XmlMapperBuilder {
    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseMapper(InputStream in) throws Exception {
        Document document = new SAXReader().read(in).getDocument();
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");
        List<Element> elements = root.selectNodes("//select|insert|update|delete");
        Map<String,MapperStatement> mapperStatementMap = configuration.getMapperStatementMap();
        MapperStatement mapperStatement = null;
        for(Element element : elements) {
            mapperStatement = new MapperStatement();
            String id = element.attributeValue("id");
            //namespace.id
            String statementId = namespace.concat(".").concat(id);
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sqlText = element.getTextTrim();
            MethodType methodType = MethodType.valueOf(element.getQualifiedName().toUpperCase(Locale.ENGLISH));


            mapperStatement.setStatementId(statementId);
            mapperStatement.setParameterType(parameterType);
            mapperStatement.setResultType(resultType);
            mapperStatement.setSqlText(sqlText);
            mapperStatement.setMethodType(methodType);

            mapperStatementMap.put(statementId,mapperStatement);
        }
    }
}
